Imports System
Imports System.Collections
Imports System.Runtime.Remoting
Imports System.Runtime.Remoting.Messaging
Imports System.Runtime.Remoting.Lifetime


Public Class ServiceClass
    Inherits MarshalByRefObject

    Private history As Queue = New Queue

    Public Event ServiceEvent As ServiceEventHandler

    Private _startTime As DateTime

    Public Sub New()
        Dim objStatus As New frmStatus
        Call objStatus.Show("ServiceClass created without constructor. Instance hash is " & Me.GetHashCode().ToString(), "ServiceClass")
        _startTime = DateTime.Now

        objStatus.Close("")
    End Sub


    <OneWay()> _
    Public Sub Send(ByVal sender As String, _
    ByVal message As String)

        Console.WriteLine(New String("-"c, 80))
        Console.WriteLine("{0} said: {1}", sender, message)
        Console.WriteLine(New String("-"c, 80))

        history.Enqueue(String.Format("At {0} {1} said: {2}", DateTime.Now, sender, message))
        DoMessageEvent(sender, message)
    End Sub


    Private Sub DoMessageEvent(ByVal sender As String, _
        ByVal message As String)

        RaiseEvent ServiceEvent(Me, _
            New ServiceEventArgs(sender, message))
    End Sub

    <OneWay()> _
    Public Sub ShowHistory()
        Dim O As Object
        For Each O In history
            DoMessageEvent("server-history", O.ToString())
        Next
    End Sub

    Protected Overrides Sub Finalize()
        Console.WriteLine("I'm being collected after " & (New TimeSpan(DateTime.Now.Ticks - _startTime.Ticks)).ToString() & " seconds.")
        MyBase.Finalize()
    End Sub

    Public Function GetServerTime() As DateTime
        Console.WriteLine("Time requested by a client.")
        Return DateTime.Now
    End Function

    Public ReadOnly Property InstanceHash() As Integer
        Get
            Return Me.GetHashCode()
        End Get
    End Property

End Class
